import {
  ArgumentsHost,
  ExceptionFilter,
  Catch,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { BusinessException } from './business.filter';
import { BUSINESS_ERROR_CODE } from '@/config/error.code';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const request = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();

    // 处理业务异常
    if (exception instanceof BusinessException) {
      const error = exception.getResponse();
      response.status(HttpStatus.OK).send({
        data: null,
        code: error['code'],
        extra: {},
        message: error['message'],
        success: false,
      });
      return;
    }
    if (exception.message == 'Unauthorized') {
      //  HTTP 异常的处理。
      response.status(200).json({
        data: 'token 过期',
        time: new Date().getTime(),
        success: false,
        path: request.url,
        code: 10007,
      });
      return;
    }
    //  HTTP 异常的处理。
    response.status(status).json({
      data: exception.message,
      time: new Date().getTime(),
      success: false,
      path: request.url,
      code: status,
    });
  }
}
